/* eslint-disable no-shadow, no-nested-ternary */
import React, { useState } from 'react';
import { Popover, Select } from 'antd';
import PropTypes from 'prop-types';
import cn from 'classnames';
import NewTopology from '@/pages/Organization/Orgs/Topology/index';
import PersonContent from '@/pages/Organization/Orgs/PersonContent';
import Person from '@/components/Topology/components/Person';
import DepartmentContent from '@/pages/Organization/Orgs/DepartmentContent';
import { eventTrack } from '@/utils/track';
import Department from '@/components/Topology/components/Department';
// import styles from '@/pages/Organization/Orgs/View.less';
// import AuthComponent from '@/utils/auth/AuthComponent';
import DrawerDepartment from '@/pages/Organization/Orgs/Topology/components/DrawerDepartment';
import DrawerEmployee from '@/pages/Organization/Orgs/Topology/components/DrawerEmployee';
import helper from '@/utils/auth/helper';
import styles from './auth.less';
// import demoData from '../demo';

const { Option } = Select;

const TopologyBox = React.forwardRef(({ isGroup, data, onDepartmentSave, onEmployeeSave, route }, ref) => {
    const [zoom, setZoom] = useState('100');
    const [treeNode, setTreeNode] = useState({});
    const [isEditDepartment, setEditDepartment] = useState(false);
    const [departmentVis, setDepartmentVis] = useState(false);
    const [employeeVis, setEmployeeVis] = useState(false);
    const hasDetailAuth = helper.checkCode('office:orgs:post:emlist:detail');
    const popConfig = hasDetailAuth ? {} : { visible: false };
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const addEmployee = ({ data }) => {
        // console.log('addEmployee=====')
        setEmployeeVis(true);
        setTreeNode(data);
    };
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const addDepartment = ({ data, isEdit }) => {
        // console.log('addDepartment=====')
        setEditDepartment(isEdit);
        setTreeNode(data);
        setDepartmentVis(true);
    };

    const renderLabel = item => {
        const {
            name,
            subChildren,
            managerPostName,
            managerName,
            employeeCount,
            employeeName,
            postName,
            cdType,
            inServiceStatus
        } = item;

        if (item.subChildren && item.subChildren.length > 0) {
            return (
                <NewTopology
                    isGroup={isGroup}
                    inner
                    className={cn('inner-topology', {
                        'no-children': !item.children || item.children.length <= 0
                    })}
                    data={[
                        {
                            ...item,
                            subChildren: [],
                            children: subChildren
                        }
                    ]}
                    labelKey={cur => cur.employeeName || cur.name}
                    subChildrenKey={cur =>
                        cur.children &&
                        cur.children.length !== 0 &&
                        (!cur.subChildren || cur.subChildren.length === 0) &&
                        cur.employeeList
                    }
                    renderSubChildren={cur => (
                        <Popover
                            // getPopupContainer={() => document.querySelector('#orgTopology')}
                            content={<PersonContent {...cur} />}
                            trigger="click"
                            {...popConfig}
                        >
                            {cur.postName}({cur.employeeName}
                            {cur.inServiceStatus === '兼任' && `-${cur.inServiceStatus}`})
                        </Popover>
                    )}
                    renderLabel={renderLabel}
                    childrenKey={cur => (cur.children && cur.children.length > 0 ? cur.children : cur.employeeList)}
                />
            );
        }
        if (employeeName) {
            return (
                <Popover
                    // getPopupContainer={() => document.querySelector('#orgTopology')}
                    content={<PersonContent {...item} />}
                    onVisibleChange={e => {
                        // 埋点
                        if (e === true) {
                            eventTrack({
                                eventName: 'organization_orgDetail_orgStaff_click',
                                eventProps: {
                                    deptment_path: `${item.companyName}-${item.name}`,
                                    employee_id: item.id
                                }
                            });
                        }
                    }}
                    trigger="click"
                    {...popConfig}
                >
                    <Person level={3} department={postName} name={employeeName} inServiceStatus={inServiceStatus} />
                </Popover>
            );
        }
        let level = 1;
        if (cdType === 1) {
            level = 3;
        }
        const person = disabled => (
            <Person
                inServiceStatus={inServiceStatus}
                department={managerPostName}
                name={managerName || '空缺'}
                disabled={disabled}
            />
        );
        return (
            <div>
                <Popover
                    // getPopupContainer={() => document.querySelector('#orgTopology')}
                    content={
                        <DepartmentContent
                            data={item}
                            onDepartmentAdd={(data, e) => {
                                e.preventDefault();
                                addDepartment({ data, isEdit: false });
                            }}
                            onDepartmentEdit={(data, e) => {
                                e.preventDefault();
                                addDepartment({ data, isEdit: true });
                            }}
                            onEmployeeAdd={(data, e) => {
                                e.preventDefault();
                                addEmployee({ data });
                            }}
                        />
                    }
                    onVisibleChange={v => {
                        // 埋点
                        if (v === true) {
                            eventTrack({
                                eventName: 'organization_orgDetail_orgDept_click',
                                eventProps: {
                                    deptment_path: `${item.companyName}-${item.name}`
                                }
                            });
                        }
                    }}
                    trigger="click"
                >
                    {!item.isCEO && (
                        <Department
                            level={level}
                            style={{ marginBottom: 4 }}
                            value={managerPostName === 'CEO' ? undefined : employeeCount}
                        >
                            {name}
                        </Department>
                    )}
                </Popover>
                {item.managerId ? (
                    <Popover
                        // getPopupContainer={() => document.querySelector('#orgTopology')}
                        content={<PersonContent showDetail={item.managerName} {...item} />}
                        trigger="click"
                        {...popConfig}
                        onVisibleChange={v => {
                            // 埋点
                            if (v === true) {
                                eventTrack({
                                    eventName: 'organization_orgDetail_orgDeptManager_click',
                                    eventProps: {
                                        deptment_path: `${item.companyName}-${item.name}`,
                                        department_manager_id: item.managerId
                                    }
                                });
                            }
                        }}
                    >
                        {person(false)}
                    </Popover>
                ) : (
                    person(true)
                )}
                {/* {(cdType === 0 || cdType === 1) && (
                    <div className={cn('addBtns', styles.addBtn)}>
                        <AuthComponent code="office:orgs:employee:department:add">
                            <Button onClick={() => addDepartment({ data: item, isEdit: false })}>+ 部门</Button>
                        </AuthComponent>
                        <AuthComponent code="office:orgs:employee:add">
                            <Button onClick={() => addEmployee({ data: item })}>+ 员工</Button>
                        </AuthComponent>
                    </div>
                )} */}
            </div>
        );
    };
    return (
        <div className={cn({ [styles.hasDetailAuth]: !hasDetailAuth })}>
            <div style={{ textAlign: 'right' }}>
                <span>缩放：</span>
                <Select
                    onChange={val => {
                        setZoom(val);
                        const topology = document.querySelector('#orgTopology');
                        if (val > 100) {
                            topology.style.transformOrigin = 'top left';
                        } else {
                            topology.style.transformOrigin = 'inherit';
                        }
                        // if (val > 100) {
                        //     const height = window.parseInt(topology.scrollHeight * val / 100);
                        //     topology.style.width = `${window.parseInt(topology.scrollWidth * val / 100)}px`;
                        //     topology.style.height = `${height}px`;
                        //     topology.style.marginTop = `${height * (val / 100 - 1)}px`;
                        // } else {
                        //     topology.style.width = 'auto';
                        //     topology.style.height = 'auto';
                        //     topology.style.marginTop = 0;
                        // }
                    }}
                    value={zoom}
                    size="small"
                >
                    <Option value="150">150%</Option>
                    <Option value="100">100%</Option>
                    <Option value="80">80%</Option>
                    <Option value="60">60%</Option>
                </Select>
            </div>
            <div ref={ref} style={{ overflowX: 'auto', overflowY: 'visible', padding: '24px 24px 48px' }}>
                <NewTopology
                    id="orgTopology"
                    isGroup={isGroup}
                    style={{
                        transform: `scale(${zoom / 100})`
                    }}
                    data={data}
                    labelKey={item => item.employeeName || item.name}
                    subChildrenKey={cur =>
                        cur.children &&
                        cur.children.length !== 0 &&
                        (!cur.subChildren || cur.subChildren.length === 0) &&
                        cur.employeeList
                    }
                    renderSubChildren={cur => (
                        <Popover
                            // getPopupContainer={() => document.querySelector('#orgTopology')}
                            content={<PersonContent {...cur} />}
                            trigger="click"
                            {...popConfig}
                        >
                            {cur.postName}({cur.employeeName}
                            {cur.inServiceStatus === '兼任' && `-${cur.inServiceStatus}`})
                        </Popover>
                    )}
                    renderLabel={renderLabel}
                    childrenKey={item => item.children || []}
                />
            </div>
            <DrawerDepartment
                modifyZIndex
                visible={departmentVis}
                onOk={() => {
                    setDepartmentVis(false);
                    onDepartmentSave();
                }}
                onCancel={() => setDepartmentVis(false)}
                treeNode={treeNode}
                isEditDepartment={isEditDepartment}
                route={route}
            />
            <DrawerEmployee
                modifyZIndex
                visible={employeeVis}
                onOk={() => {
                    setEmployeeVis(false);
                    onEmployeeSave();
                }}
                treeNode={treeNode}
                isEditDepartment={isEditDepartment}
                onCancel={() => setEmployeeVis(false)}
            />
        </div>
    );
});

TopologyBox.propTypes = {
    isGroup: PropTypes.bool,
    data: PropTypes.array,
    onDepartmentSave: PropTypes.func,
    onEmployeeSave: PropTypes.func
};

TopologyBox.defaultProps = {
    isGroup: false,
    data: [],
    onDepartmentSave: () => {},
    onEmployeeSave: () => {}
};

export default TopologyBox;
